﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace DIProject.Stock
{	public partial class Disgather : Form
	{	private	Util.ActionType actionType;
		private	Disgathers disgathers;
//-------------------------------------------------------------------------------------------------
		private	DIProject.DataSets.Stock.DisgathersRow disgathersRow = null;
		private	int? docId{get{return disgathersRow != null? (int?)disgathersRow.Id: null;}}
//-------------------------------------------------------------------------------------------------
		public Disgather() : this(Util.ActionType.NoAction, null)
		{
		}

		public Disgather(Util.ActionType actionType, Disgathers disgathers)
		{	InitializeComponent();
			textFormat = Text;
			this.actionType	= actionType;
			this.disgathers	= disgathers;
			if(actionType != DIProject.Util.ActionType.Insert
			&& disgathers != null
			&& disgathers.disgathersGridView.CurrentCell != null)
				disgathersRow = (DIProject.DataSets.Stock.DisgathersRow)((DataRowView)disgathers.disgathersGridView.CurrentCell.OwningRow.DataBoundItem).Row;
		}
//-------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------
		private readonly string textFormat;
//-------------------------------------------------------------------------------------------------
		private void Disgather_Load(object sender, EventArgs e)
		{	string text = null;
			Binding binding;
			DIProject.DataSets.Stock.DisgatherRow disgatherRow = null;
			try
			{	if(actionType == DIProject.Util.ActionType.Insert)
				{	disgatherRow = stock.Disgather.NewDisgatherRow();
					disgatherRow.DocDate= DateTime.Today;
					disgatherRow.MD		= DateTime.Now;
					disgatherRow.MW		= FirstForm.Login;
					stock.Disgather.AddDisgatherRow(disgatherRow);

					text = DIProject.Properties.Resources.strNewDisgatherDoc;
				}
				else
				{	buttonParty.Enabled	= false;
					textBoxNote.Enabled	= false;
					buttonAccept.Visible= false;
					buttonAccept.Enabled= false;
					buttonCancel.Text	= Properties.Resources.strClose;
					AcceptButton		= buttonCancel;
					if(docId != null)
					{	disgatherTableAdapter.Fill(stock.Disgather, (int)docId);
						if(stock.Disgather.Count > 0)
							disgatherRow = stock.Disgather[0];
					}

					text = string.Format(textFormat, disgatherRow.DocNumber, disgatherRow.DocDate);
				}
				textBoxName0		.DataBindings.Add("Text", disgatherRow, "GoodsName0"		);
				textBoxManufacturer	.DataBindings.Add("Text", disgatherRow, "ManufacturerName"	);
				textBoxBarcode0		.DataBindings.Add("Text", disgatherRow, "Barcode0"			);
				textBoxQntty0		.DataBindings.Add("Text" ,disgatherRow, "Qntty0"			);
				binding					= new Binding("Text", disgatherRow, "RetailPrice0"		);
				binding.Format += new ConvertEventHandler(price_Format);
				textBoxPrice0		.DataBindings.Add(binding);

				textBoxName1		.DataBindings.Add("Text", disgatherRow, "GoodsName1"		);

				textBoxBarcode1		.DataBindings.Add("Text", disgatherRow, "Barcode1"			);
				textBoxQntty1		.DataBindings.Add("Text", disgatherRow, "Qntty1"			);
				binding					= new Binding("Text", disgatherRow, "RetailPrice1"		);
				binding.Format += new ConvertEventHandler(price_Format);
				textBoxPrice1		.DataBindings.Add(binding);

				textBoxBarcode2		.DataBindings.Add("Text", disgatherRow, "Barcode2",false,DataSourceUpdateMode.Never,string.Empty);
                textBoxQntty2.DataBindings.Add("Text", disgatherRow, "Qntty2", false, DataSourceUpdateMode.Never, string.Empty);
                binding = new Binding("Text", disgatherRow, "RetailPrice2", true, DataSourceUpdateMode.Never, string.Empty);
				binding.Format += new ConvertEventHandler(price_Format);
				textBoxPrice2		.DataBindings.Add(binding);

				textBoxNote			.DataBindings.Add("Text", disgatherRow, "Note",false,DataSourceUpdateMode.Never,string.Empty				);
			}
			catch(SqlException eq)
			{	MessageBox.Show(this, string.Format("{0} ({1}): {2}", eq.Procedure, eq.LineNumber, eq.Message), Properties.Resources.strError, MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
			catch(Exception ex)
			{	MessageBox.Show(this, ex.Message, Properties.Resources.strError, MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
			Text = text;
		}
//-------------------------------------------------------------------------------------------------
		private void price_Format(object sender, ConvertEventArgs e)
		{	if(e.DesiredType == typeof(string))
				e.Value = e.Value is decimal? ((decimal)e.Value).ToString("N2"): string.Empty;
		}
//-------------------------------------------------------------------------------------------------
		private void buttonParty_Click(object sender, EventArgs e)
		{	
            if(stock.Disgather.Count > 0)
			{	DIProject.DataSets.Stock.DisgatherRow disgatherRow = stock.Disgather[0];
				PartyChoice partyChoice = new PartyChoice(null, true, null, null);
				partyChoice.PartiesBindingSource.Filter = "AllowUnPack=true";
				if(partyChoice.ShowDialog(this) == DialogResult.OK)
				{	BindingManagerBase bindingManager = BindingContext[disgatherRow];
					bindingManager.SuspendBinding();

					DIProject.DataSets.Dictionary.PartiesRow parentRow = partyChoice.CurrentRow;
					int parentRetailPack			= parentRow.RetailPack;
					int parentGoodsId				= parentRow.GoodsId;
					decimal parentPrice				= parentRow.RetailPrice;
					disgatherRow.PartyId			= parentRow.Id;					// Партия-источник
					disgatherRow.GoodsName0			= parentRow.Name;
					disgatherRow.ManufacturerName	= parentRow.ManufacturerName;
					disgatherRow.Barcode0			= parentRow.Barcode;
					disgatherRow.RetailPrice0		= parentRow.RetailPrice;

					disgatheredGoodsTableAdapter.Fill(stock.DisgatheredGoods, parentGoodsId);
					if(stock.DisgatheredGoods.Count > 0)
					{	DIProject.DataSets.Stock.DisgatheredGoodsRow childRow = stock.DisgatheredGoods[0];
						int childRetailPack		= childRow.RetailPack;
						int childGoodsId		= childRow.Id;
						disgatherRow.GoodsId	= childRow.Id;						// Товар-приёмник
						disgatherRow.GoodsName1	= childRow.FullName;

                        #region деление товара
                        int		childQntty = parentRetailPack/childRetailPack;
                        int test = parentRetailPack % childRetailPack;
                        if (test != 0)
                        {
                            MessageBox.Show("Невозможно разделить товар! Количество в родительском товаре в разделяемой упаковке не делиться нацело на количество в дочерней!");
                            return;
                        }
						decimal	childPrice = parentPrice/childQntty;
                        //количество меньше 2 - делить нельзя!
                        if (childQntty < 2)
                        {
                            MessageBox.Show("Невозможно разделить товар!");
                            return;
                        }
                        //в любом случае создаем 2 партии
                        childPrice = decimal.Floor(childPrice * 100m) / 100m;	// до 1 копеек
                        --childQntty;
                        disgatherRow.RetailPrice1 = parentPrice - childPrice * childQntty;
                        disgatherRow.Qntty1 = 1;
                        disgatherRow.RetailPrice2 = childPrice;
                        disgatherRow.Qntty2 = childQntty;
                        #endregion
                        #region старый закоментированный код
                        /*
                        if (childPrice != decimal.Round(childPrice, 2))		// до 10 копеек
						{	--childQntty;
							childPrice = decimal.Floor(childPrice*100m)/100m;	// до 1 копеек
                           // decimal dTmp = parentPrice - childPrice * childQntty;
                           // decimal dTmp1 = parentPrice - (childPrice + 0.1) * childQntty;
							disgatherRow.RetailPrice1	= parentPrice - childPrice*childQntty;
							disgatherRow.Qntty1			= 1;

							disgatherRow.RetailPrice2	= childPrice;
							disgatherRow.Qntty2			= childQntty;
						}
						else
						{	disgatherRow.RetailPrice1	= childPrice;
							disgatherRow.Qntty1			= childQntty;
                            disgatherRow.SetRetailPrice2Null();
                            disgatherRow.SetQntty2Null();
                        }
                         * */
                        #endregion
                    }

					bindingManager.ResumeBinding();
				}
			}
		}
//-------------------------------------------------------------------------------------------------
		private void buttonAccept_Click(object sender, EventArgs e)
		{	if(stock.Disgather.Count > 0)
			{	DIProject.DataSets.Stock.DisgatherRow disgatherRow = stock.Disgather[0];
				try
				{	disgatherTableAdapter.Update(disgatherRow);
					int id = disgatherRow.Id;
					disgatherTableAdapter.Fill(stock.Disgather, id);
					if(stock.Disgather.Count > 0)
					{	disgatherRow = stock.Disgather[0];
						textBoxBarcode1.Text = disgatherRow.Barcode1;
						textBoxBarcode2.Text = disgatherRow.Barcode2;
						Text = string.Format(textFormat, disgatherRow.DocNumber, disgatherRow.DocDate);
					}
					if(disgathers != null && stock.Disgather.Count > 0)
					{	disgathers.stock.Disgathers.AddDisgathersRow
						(	disgatherRow.DocDate
						,	disgatherRow.DocNumber
						,	disgatherRow.Note
						,	disgatherRow.MD
						,	disgatherRow.MW
						,	disgatherRow.GoodsName0
						,	disgatherRow.ManufacturerName
						,	disgatherRow.Barcode0
						,	disgatherRow.RetailPrice0
						);
						disgathers.disgathersGridView.CurrentCell = disgathers.disgathersGridView.Rows[disgathers.disgathersGridView.Rows.Count - 1].Cells[disgathers.disgathersGridView.CurrentCell.ColumnIndex];
						disgathersRow = (DIProject.DataSets.Stock.DisgathersRow)((DataRowView)disgathers.disgathersGridView.CurrentCell.OwningRow.DataBoundItem).Row;
						disgathersRow.Id = id;
					}
					buttonParty.Enabled	= false;
					textBoxNote.Enabled	= false;
					buttonAccept.Visible= false;
					buttonAccept.Enabled= false;
					buttonCancel.Text	= Properties.Resources.strClose;
					AcceptButton		= buttonCancel;

					if(disgathersRow != null)
						disgathersRow.AcceptChanges();
					stock.Disgather.AcceptChanges();
				}
				catch(SqlException eq)
				{	if(disgathersRow != null)
						disgathersRow.RejectChanges();
					MessageBox.Show(this, string.Format("{0} ({1}): {2}", eq.Procedure, eq.LineNumber, eq.Message), Properties.Resources.strError, MessageBoxButtons.OK, MessageBoxIcon.Error);
				}
				catch(Exception ex)
				{	if(disgathersRow != null)
						disgathersRow.RejectChanges();
					MessageBox.Show(this, ex.Message, Properties.Resources.strError, MessageBoxButtons.OK, MessageBoxIcon.Error);
				}
			}
		}
//-------------------------------------------------------------------------------------------------
	}
}